<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat接口测试页面</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }

        .container {
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }

        .input-section {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: bold;
            color: #555;
        }

        input[type="text"] {
            width: 100%;
            padding: 12px;
            border: 2px solid #ddd;
            border-radius: 6px;
            font-size: 16px;
            box-sizing: border-box;
        }

        input[type="text"]:focus {
            outline: none;
            border-color: #4CAF50;
        }

        .button-section {
            text-align: center;
            margin-bottom: 30px;
        }

        button {
            background-color: #4CAF50;
            color: white;
            padding: 12px 30px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 16px;
            margin: 0 10px;
        }

        button:hover {
            background-color: #45a049;
        }

        button:disabled {
            background-color: #cccccc;
            cursor: not-allowed;
        }

        #stopBtn {
            background-color: #f44336;
        }

        #stopBtn:hover {
            background-color: #da190b;
        }

        .response-section {
            margin-top: 20px;
        }

        #responseArea {
            width: 100%;
            min-height: 300px;
            padding: 15px;
            border: 2px solid #ddd;
            border-radius: 6px;
            background-color: #f9f9f9;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            white-space: pre-wrap;
            overflow-y: auto;
            box-sizing: border-box;
        }

        .status {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            font-weight: bold;
        }

        .status.connecting {
            background-color: #fff3cd;
            color: #856404;
            border: 1px solid #ffeaa7;
        }

        .status.connected {
            background-color: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }

        .status.error {
            background-color: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }

        .status.completed {
            background-color: #d1ecf1;
            color: #0c5460;
            border: 1px solid #bee5eb;
        }

        .api-info {
            background-color: #e7f3ff;
            border: 1px solid #b3d9ff;
            border-radius: 6px;
            padding: 15px;
            margin-bottom: 20px;
        }

        .api-info h3 {
            margin-top: 0;
            color: #0066cc;
        }

        .api-info code {
            background-color: #f1f1f1;
            padding: 2px 6px;
            border-radius: 3px;
            font-family: 'Courier New', monospace;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🩺 Healio Chat接口测试</h1>

        <div class="api-info">
            <h3>接口信息</h3>
            <p><strong>URL:</strong> <code>GET /test/chat</code></p>
            <p><strong>参数:</strong> <code>query</code> - 用户输入的问题</p>
            <p><strong>返回:</strong> Server-Sent Events (SSE) 流式数据</p>
            <p><strong>说明:</strong> 该接口会调用医疗团队主席Smith来回答用户问题</p>
        </div>

        <div class="input-section">
            <label for="queryInput">请输入您的问题:</label>
            <input type="text" id="queryInput" placeholder="例如: 我最近总是头痛，可能是什么原因？"
                   value="我最近总是头痛，可能是什么原因？">
        </div>

        <div class="button-section">
            <button id="sendBtn" onclick="sendQuery()">发送问题</button>
            <button id="stopBtn" onclick="stopStream()" disabled>停止接收</button>
            <button onclick="clearResponse()">清空响应</button>
        </div>

        <div class="response-section">
            <label for="responseArea">实时响应:</label>
            <textarea id="responseArea" readonly></textarea>
        </div>

        <div id="status" class="status" style="display: none;"></div>
    </div>

    <script>
        let eventSource = null;
        let isConnected = false;

        function updateStatus(message, type) {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = message;
            statusDiv.className = 'status ' + type;
            statusDiv.style.display = 'block';
        }

        function sendQuery() {
            const query = document.getElementById('queryInput').value.trim();
            if (!query) {
                alert('请输入问题！');
                return;
            }

            // 如果已有连接，先关闭
            if (eventSource) {
                eventSource.close();
            }

            // 清空响应区域
            document.getElementById('responseArea').value = '';

            // 更新按钮状态
            document.getElementById('sendBtn').disabled = true;
            document.getElementById('stopBtn').disabled = false;

            updateStatus('正在连接...', 'connecting');

            // 创建SSE连接
            const encodedQuery = encodeURIComponent(query);
            const url = `/test/chat?query=${encodedQuery}`;

            eventSource = new EventSource(url);

            eventSource.onopen = function(event) {
                isConnected = true;
                updateStatus('连接成功，等待响应...', 'connected');
                console.log('SSE连接已建立', event);

                // 添加调试信息
                const responseArea = document.getElementById('responseArea');
                responseArea.value += '[调试] SSE连接已建立，等待数据...\n';
            };

            eventSource.onmessage = function(event) {
                console.log('收到数据:', event.data);
                const responseArea = document.getElementById('responseArea');

                try {
                    // 尝试解析JSON数据
                    const data = JSON.parse(event.data);
                    if (data.type === 'data' && data.content) {
                        responseArea.value += data.content + '\n';
                    } else if (data.type === 'progress') {
                        responseArea.value += `[进度] ${data.progress}% - ${data.message}\n`;
                    } else {
                        responseArea.value += event.data + '\n';
                    }
                } catch (e) {
                    // 如果不是JSON，直接显示原始数据
                    responseArea.value += event.data + '\n';
                }

                // 自动滚动到底部
                responseArea.scrollTop = responseArea.scrollHeight;

                updateStatus('正在接收数据...', 'connected');
            };

            eventSource.onerror = function(event) {
                console.error('SSE连接错误:', event);
                console.log('EventSource readyState:', eventSource.readyState);
                console.log('EventSource.CONNECTING:', EventSource.CONNECTING);
                console.log('EventSource.OPEN:', EventSource.OPEN);
                console.log('EventSource.CLOSED:', EventSource.CLOSED);

                const responseArea = document.getElementById('responseArea');
                responseArea.value += `[调试] SSE连接错误，readyState: ${eventSource.readyState}\n`;

                if (eventSource.readyState === EventSource.CLOSED) {
                    updateStatus('连接已关闭', 'completed');
                    responseArea.value += '[调试] 连接已正常关闭\n';
                } else {
                    updateStatus('连接发生错误', 'error');
                    responseArea.value += '[调试] 连接发生错误\n';
                }

                // 重置按钮状态
                document.getElementById('sendBtn').disabled = false;
                document.getElementById('stopBtn').disabled = true;
                isConnected = false;
            };

            eventSource.onclose = function(event) {
                console.log('SSE连接已关闭');
                updateStatus('响应完成', 'completed');

                // 重置按钮状态
                document.getElementById('sendBtn').disabled = false;
                document.getElementById('stopBtn').disabled = true;
                isConnected = false;
            };
        }

        function stopStream() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
                updateStatus('已手动停止连接', 'completed');
            }

            // 重置按钮状态
            document.getElementById('sendBtn').disabled = false;
            document.getElementById('stopBtn').disabled = true;
            isConnected = false;
        }

        function clearResponse() {
            document.getElementById('responseArea').value = '';
            document.getElementById('status').style.display = 'none';
        }

        // 回车键发送
        document.getElementById('queryInput').addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendQuery();
            }
        });

        // 页面卸载时关闭连接
        window.addEventListener('beforeunload', function() {
            if (eventSource) {
                eventSource.close();
            }
        });
    </script>
</body>
</html>

